package com.ll.gulimall.cart.controller;

import com.ll.gulimall.cart.interceptor.CartInterceptor;
import com.ll.gulimall.cart.service.CartService;
import com.ll.gulimall.cart.to.UserInfoTo;
import com.ll.gulimall.cart.vo.Cart;
import com.ll.gulimall.cart.vo.CartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.concurrent.ExecutionException;

@Controller
public class CartController {
    @Autowired
    CartService cartService;


    /**
     * 获取用户购物项选中的
     *
     * @return
     */
    @GetMapping("/userCartItems")
    @ResponseBody
    public List<CartItem> userCartItems() {

        return cartService.getUserCartItems();

    }

    /*
     * 获取购物车数据
     *
     * @return
     */
    @GetMapping("/cart.html")
    public String cartInfoPage(Model model) throws ExecutionException, InterruptedException {
        Cart cart = cartService.getCart();
        model.addAttribute("cart", cart);
        return "cartList";
    }

    //checkedItem?skuId=" + skuId + "&checked=" + (checked ? 1 : 0);
    @GetMapping("/checkedItem")
    public String checkedItem(@RequestParam("skuId") Long skuId, @RequestParam("checked") Integer checked) {

        cartService.checkedItem(skuId, checked);

        return "redirect:http://cart.gulimall.com/cart.html";
    }

    //"http://cart.gulimall.com/changeNum?skuId=" + skuId + "&num=" + num;
    @GetMapping("/changeNum")
    public String changeNum(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num) {

        cartService.changeNum(skuId, num);

        return "redirect:http://cart.gulimall.com/cart.html";
    }

    //http://cart.gulimall.com/delCartItem?skuId=" + skuId;

    @GetMapping("/delCartItem")
    public String delCartItem(@RequestParam("skuId") Long skuId) {

        cartService.delCartItem(skuId);

        return "redirect:http://cart.gulimall.com/cart.html";
    }

    @GetMapping("/addToCart")
    public String addToCart(@RequestParam("skuId") String skuId, @RequestParam("num") Integer num, RedirectAttributes re) throws ExecutionException, InterruptedException {
        cartService.addToCart(skuId, num);
        re.addAttribute("skuId", skuId);
        return "redirect:http://cart.gulimall.com/addToCartSuccess.html";
    }

    @GetMapping("/addToCartSuccess.html")
    public String addToCartSuccess(@RequestParam("skuId") String skuId, Model model) {
        CartItem cartItem = cartService.getCartItem(skuId);
        model.addAttribute("cartItem", cartItem);
        return "success";

    }

}
